package com.tbit.uqbike.client.service.impl;

import com.alibaba.fastjson.JSON;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.tbit.uqbike.client.constant.CommonConstant;
import com.tbit.uqbike.client.dao.core.AccountConfigExtDao;
import com.tbit.uqbike.client.pojo.AccountConfig;
import com.tbit.uqbike.client.pojo.newEntity.AccountConfigExt;
import com.tbit.uqbike.client.service.AccountConfigService;
import com.tbit.uqbike.client.service.CacheService;
import com.tbit.uqbike.client.util.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.net.Inet4Address;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 代理商配置
 *
 * @author Leon
 * 2019年11月19日 上午10:49:57
 */
@Slf4j
@Service
public class AccountConfigServiceImpl implements AccountConfigService {
    @Autowired
    private CacheService cacheService;
    @Autowired
    private AccountConfigExtDao accountConfigExtDao;


    @Override
    public AccountConfig getByAccountId(Integer accountId) {
        return cacheService.getConfig(accountId);
    }

    /**
     * @description: 检查是否设置了设备离线后禁止发送蓝牙指令，同时检查当前时间和上一次车辆在线时间是否超过了设置的时间
     * @author: mo.shanyong
     * @date: 2024/12/2 13:55
     * @param: accountId 区域id（车辆的账号id）
     * @param: batDt 终端最后状态的电池信息时间(0000-00-00 00:00:00)
     * @param: machineType 设备类型
     * @return: boolean
     */
    @Override
    public boolean checkAccountConfigExt(Integer accountId, String batDt,Integer machineType) {
        log.info("accountId:{},batDt:{},machineType:{}",accountId,batDt,machineType);
        //如果车辆在线，则直接返回true
        if (this.getOnline(batDt,machineType)){
            log.info("监测到不是离线状态");
            return false;
        }
        //获取设备离线后禁止发送蓝牙指令
        List<AccountConfigExt> accountConfigExts = accountConfigExtDao.selectByAccountIdAndKeys(accountId, new HashSet<>(Arrays.asList(CommonConstant.BLUETOOTH_SEND_MACHINE_SWITCH,
                CommonConstant.BLUETOOTH_SEND_MACHINE_TIME)));
        log.info("accountConfigExts:{}", JSON.toJSONString(accountConfigExts));
        if (CollectionUtils.isEmpty(accountConfigExts)){
            return false;
        }
        Map<String, String> paramMap = accountConfigExts.stream().
                collect(Collectors.toMap(AccountConfigExt::getParamKey, AccountConfigExt::getParamValue));
        //设备离线后禁止发送蓝牙指令开关
        String bluetoothSendMachineSwitch = paramMap.get(CommonConstant.BLUETOOTH_SEND_MACHINE_SWITCH);
        //没开的话不做校验
        if (!Objects.equals(bluetoothSendMachineSwitch,CommonConstant.BLUETOOTH_SEND_MACHINE_SWITCH_OPEN)){
            return false;
        }
        //获取设置的间隔分钟
        String time = paramMap.get(CommonConstant.BLUETOOTH_SEND_MACHINE_TIME).replaceAll(",","");
        int intervalSeconds = Integer.parseInt(time);
        log.info("intervalSeconds:{}",intervalSeconds);
        if (DateTimeUtil.checkTimeAndNowInterval(batDt) >= (intervalSeconds * 60 * 1000L)){
            return true;
        }
        return false;
    }


    /**
     * 获取线上状态
     *
     * @return
     */
    private boolean getOnline(String batDt, Integer machineType) {
        SimpleDateFormat dateFormat = DateTimeUtil.getSdf_yyyyMMddHHmmss();
        if (StringUtils.isBlank(batDt)) {//如果为空，无法计算当前时间和设备最后在线时间的间隔时间，所以直接返回true
            return true;
        } else {
            int terOfflineSec = machineType == 0 ? CommonConstant.TerOfflineSec : CommonConstant.BIKE_TER_OFFLINE_SEC;
            try {
                return (System.currentTimeMillis() - dateFormat.parse(batDt).getTime()) < terOfflineSec * 1000L;
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
